/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.SavingBookManager;

import BLL.Unity;
import BLL.WithDraw_BLL;
import DAL.ConnectUnit;
import DTO.WithDraw_DTO;
import java.awt.Frame;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import static javax.swing.WindowConstants.HIDE_ON_CLOSE;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Nguyen Phi Hung
 */
public class JF_WithDraw extends javax.swing.JFrame {
    
    Unity unity=new Unity();
    WithDraw_BLL withdraw_bll=new WithDraw_BLL();
    int SoNgayGuiTien;
    int SoNgayGuiToiThieu;
    int KyHan=SavingBookManager.txt_KyHan;
    float SoTienHienTai=withdraw_bll.SoTienHienTai_STK("{call SoTienHienTai_STK(?,?)}", SavingBookManager.txtMaSo);
    float SoTienRutToiThieu=withdraw_bll.SoTienRutToiThieu("{call SoTienRutToiThieu_STK(?)}");
    /**
     * Creates new form JF_WithDraw
     */
    public JF_WithDraw() throws Exception {
        initComponents();
        MaSo.setText(SavingBookManager.txtMaSo);
        CMND.setDocument(getPlainDocument(11));
        init();
        NgayRut.setDate(new Date());
        NgayRut.setEditable(false);
        SoNgayGuiToiThieu=withdraw_bll.SoNgayGuiTienToiThieu("{call SoNgayGuiToiThieu_STK(?)}");
        SoNgayGuiTien=withdraw_bll.SoNgayGuiTien("{call SoNgayGui_STK(?,?,?)}", MaSo.getText().trim(), unity.ConvertDate(NgayRut));
    }
    public void init()
    {
        try {
            if(KyHan==-1)
            {
                SoTienRut.setText("0.0");
            }
            if(KyHan>0)
            {
                SoTienRut.setText(SoTienHienTai+"");
                SoTienRut.setEditable(false);
            }
        } catch (Exception ex) {
            Logger.getLogger(JF_WithDraw.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static PlainDocument getPlainDocument(final int maxLength) {
        PlainDocument p = new PlainDocument() {
            @Override
            public void insertString(int arg0, String arg1, AttributeSet arg2)
                    throws BadLocationException {
// TODO Auto-generated method stub
                if (getLength() + arg1.length() <= maxLength) {
                    super.insertString(arg0, arg1, arg2);
                }
            }
        };
        return p;
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel3 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        MaSo = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        HoTen = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        CMND = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        SoTienRut = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        NgayRut = new org.jdesktop.swingx.JXDatePicker();
        RutTien = new javax.swing.JButton();
        XuatPhieu = new javax.swing.JButton();
        NhapLai = new javax.swing.JButton();

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${defaultCloseOperation}"), this, org.jdesktop.beansbinding.BeanProperty.create("defaultCloseOperation"));
        bindingGroup.addBinding(binding);

        jLabel9.setText("Mã Sổ");

        jLabel10.setText("Họ Tên");

        HoTen.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                HoTenKeyTyped(evt);
            }
        });

        jLabel11.setText("CMND");

        CMND.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CMNDActionPerformed(evt);
            }
        });
        CMND.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                CMNDKeyTyped(evt);
            }
        });

        jLabel12.setText("Số Tiền Rút");

        SoTienRut.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                SoTienRutKeyTyped(evt);
            }
        });

        jLabel13.setText("Ngày Rút");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(43, 43, 43)
                        .addComponent(MaSo, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37)
                        .addComponent(jLabel12))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel11))
                        .addGap(38, 38, 38)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(HoTen, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(35, 35, 35)
                                .addComponent(jLabel13))
                            .addComponent(CMND, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(SoTienRut, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NgayRut, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(MaSo, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(HoTen, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(SoTienRut, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(NgayRut, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CMND, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        RutTien.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_Save.png"))); // NOI18N
        RutTien.setText("Rút Tiền");
        RutTien.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RutTienActionPerformed(evt);
            }
        });

        XuatPhieu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_TradeBill.png"))); // NOI18N
        XuatPhieu.setText("Xuất Phiếu");
        XuatPhieu.setEnabled(false);
        XuatPhieu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                XuatPhieuActionPerformed(evt);
            }
        });

        NhapLai.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/Small_Update.png"))); // NOI18N
        NhapLai.setText("Nhập Lại");
        NhapLai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NhapLaiActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(RutTien, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(XuatPhieu, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addComponent(NhapLai, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(RutTien, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(XuatPhieu, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NhapLai, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void HoTenKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_HoTenKeyTyped
        // TODO add your handling code here:
        char c=evt.getKeyChar();
        if((c<32)||(c>32&&c<65)||(90<c&&c<97)||c>122)
        {
            evt.consume();
        }
    }//GEN-LAST:event_HoTenKeyTyped

    private void CMNDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CMNDActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_CMNDActionPerformed

    private void CMNDKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CMNDKeyTyped
        // TODO add your handling code here:
        char c=evt.getKeyChar();
        if((c<48||c>57))
        {
            evt.consume();
        }
    }//GEN-LAST:event_CMNDKeyTyped

    private void SoTienRutKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_SoTienRutKeyTyped
        // TODO add your handling code here:
        char c=evt.getKeyChar();
        if((c<48||c>57))
        {
            evt.consume();
        }
    }//GEN-LAST:event_SoTienRutKeyTyped

    private void RutTienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RutTienActionPerformed
        try {
            // TODO add your handling code here:
            WithDraw_DTO info=new WithDraw_DTO();
            info.setBookID(MaSo.getText().trim());
            info.setCustomerName(HoTen.getText().trim());
            info.setIDNumber(CMND.getText().trim());
            info.setWithdrawingDate(unity.ConvertDate(NgayRut));
            info.setAmountOfMoney(Float.parseFloat(SoTienRut.getText().trim()));
            
            /* 
             * kiểm tra số họ tên, cmnd có tồn tại trên hệ thống hay không,
             * nếu có thì kiểm tra xem khách hàng có sở hữu mã sổ được rút tiền hay không
             * kiểm tra số tiền rút
             * kiểm tra ngày rút tiền có thõa mãn theo quy định hay không.
             */
            if(withdraw_bll.KiemTraThongTin_KH("{call Check_Customer(?,?,?)}", info.getCustomerName(), info.getIDNumber()))
            {
                if(withdraw_bll.KiemTraMaSoThuocKH("{call KiemTraMaSoThuocKH(?,?,?,?)}", info.getBookID(),info.getCustomerName(), info.getIDNumber()))
                {
                    if(withdraw_bll.KiemTraSoTienRut("{call KiemTra_SoTienRut(?,?,?)}", info.getBookID(),info.getAmountOfMoney()))
                    {
                        if(SoNgayGuiTien>=SoNgayGuiToiThieu)
                        {
                            withdraw_bll.Insert("{call Insert_WithDraw(?,?,?,?,?)}", info);
                            JOptionPane.showMessageDialog(null, "Rút Thành Công");
                            XuatPhieu.setEnabled(true);
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(null, "Ngày Rút Tiền Phải Sau Ngày Mở Sổ Tiết Kiêm là "+SoNgayGuiToiThieu);
                        }
                        
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"Số Tiền rút Không Hợp Lệ, Số Tiền Rút Phải Lớn Hơn"+SoTienRutToiThieu+" Và Nhỏ Hơn "+SoTienHienTai);
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Khách Hàng Không Sở Hữu Sổ Tiết Kiệm Này");
                }
                        
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Khách Hàng Chưa Tồn Tại Trên Hệ Thống");
            }
            //deposit_bll.Insert("{call Insert_Deposit(?,?,?,?,?)}", info);
                    //JOptionPane.showMessageDialog(null, "Gửi Thành Công");
            //JOptionPane.showMessageDialog(null, info.getAmountOfMoney());
            //kiem tra so tien gui
    /*
            try {
                boolean KiemTraSoTienGui=deposit_bll.KiemTraSoTienGui("{call KiemTra_SoTienGui(?,?)}", info.getAmountOfMoney());
                if(KiemTraSoTienGui)
                {
                    deposit_bll.Insert("{call Insert_Deposit(?,?,?,?,?)}", info);
                    JOptionPane.showMessageDialog(null, "Gửi Thành Công");
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Số Tiền Gửi Phải Lớn Hơn Số Tiền Gửi Tối Thiểu");
                }

            } catch (Exception e) {
            }
            * */
        } catch (Exception ex) {
            Logger.getLogger(JF_WithDraw.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_RutTienActionPerformed

    private void XuatPhieuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_XuatPhieuActionPerformed
        try {
            new JF_WithDraw().ShowReport();
        } catch (Exception ex) {
            Logger.getLogger(JF_WithDraw.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_XuatPhieuActionPerformed

    private void NhapLaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NhapLaiActionPerformed
        // TODO add your handling code here:
        HoTen.setText("");
        CMND.setText("");
        SoTienRut.setText("0.0");

    }//GEN-LAST:event_NhapLaiActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JF_WithDraw.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JF_WithDraw.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JF_WithDraw.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JF_WithDraw.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new JF_WithDraw().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(JF_WithDraw.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField CMND;
    private javax.swing.JTextField HoTen;
    private javax.swing.JTextField MaSo;
    private org.jdesktop.swingx.JXDatePicker NgayRut;
    private javax.swing.JButton NhapLai;
    private javax.swing.JButton RutTien;
    private javax.swing.JTextField SoTienRut;
    private javax.swing.JButton XuatPhieu;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel3;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private void ShowReport() throws JRException, Exception {
        JasperReport report = JasperCompileManager.compileReport("src\\report\\report_withdraw.jrxml");
        HashMap parameters = new HashMap();
        //parameters.put("DepositingDate", "'25/06/2013'");
        ConnectUnit connection = DAL.DAL.getDAL();
        Connection con = connection.connect.getConnect();
        JasperPrint print = JasperFillManager.fillReport(report, null, con);
        JRViewer viewer = new JRViewer(print);            

        viewer.setVisible(true);

        JasperViewer view = new JasperViewer(print);
        view.viewReport(print);
        
        view.setExtendedState(Frame.MAXIMIZED_BOTH);
        view.setDefaultCloseOperation(HIDE_ON_CLOSE);
    }
}
